/**
 * Copyright (C) 2014  Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
 *
 * This file is part of Dicoogle/dicoogle.
 *
 * Dicoogle/dicoogle is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Dicoogle/dicoogle is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Dicoogle.  If not, see <http://www.gnu.org/licenses/>.
 */
package pt.ua.dicoogle.rGUI.client.windows;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.net.URL;
import java.util.concurrent.Semaphore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.skin.BusinessBlackSteelSkin;


import pt.ua.dicoogle.rGUI.client.ConnectServer;

import pt.ua.dicoogle.Main;
import pt.ua.dicoogle.core.ClientSettings;
import pt.ua.dicoogle.server.users.HashService;


/**
 *
 * @author Samuel Campos <samuelcampos@ua.pt>
 */
@Deprecated
public class ConnectWindow extends javax.swing.JFrame {

    private static ConnectWindow instance;
    private static Semaphore sem = new Semaphore(1, true);

    private boolean isUsingDefaultPass = false;

    public static synchronized ConnectWindow getInstance()
    {
        try
        {
            sem.acquire();
            if (instance == null)
            {
                instance = new ConnectWindow();
            }
            sem.release();
        }
        catch (InterruptedException ex)
        {
            LoggerFactory.getLogger(ConnectWindow.class).error(ex.getMessage(), ex);
        }
        return instance;
    }


    public static Image getImage(final String pathAndFileName) {
        final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
        return Toolkit.getDefaultToolkit().getImage(url);
    }
    
    
    /** Creates new form ConnectWindow */
    private ConnectWindow() {
        
        initComponents();
        // change to Dicoogle Default Skin
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SubstanceLookAndFeel.setSkin(new BusinessBlackSteelSkin());
            }
        });

        Image image = getImage("trayicon.gif");
        this.setIconImage(image);

        // Positions the window in the center of screen
        int width = this.getWidth();
        int height = this.getHeight();
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (screen.width-width)/2;
        int y = (screen.height-height)/2;
        setBounds(x,y,width,height);
        
        
        jLabel8.setVisible(false);

        ClientSettings settings = ClientSettings.getInstance();
        Host.setText(settings.getDefaultServerHost());
        Port.setText(String.valueOf(settings.getDefaultServerPort()));
        User.setText(settings.getDefaultUserName());

        if(settings.getDefaultPassword() != null && !settings.getDefaultPassword().equals(""))
        {
            Pass.setText("lixo_lixo_lixo");
            isUsingDefaultPass = true;
            ConnectButton.grabFocus();
        }
        else
            Pass.grabFocus();
        
        if(Main.isFixedClient()){
            Host.setEnabled(false);
            Port.setEnabled(false);
            Port.setText(Main.getRemoteGUIPort() + "");
        }

        //this.setVisible(true);

        // set this window visible
       SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                ConnectWindow.getInstance().setVisible(true);

                if(ClientSettings.getInstance().getAutoConnect())
                    ConnectWindow.getInstance().ConnectButtonActionPerformed(null);
            }
        });
       

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        Port = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        ConnectButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        Host = new javax.swing.JTextField();
        User = new javax.swing.JTextField();
        Pass = new javax.swing.JPasswordField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Dicoogle GUI Connector");
        setResizable(false);

        jLabel4.setText("Port:");

        Port.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                PortKeyPressed(evt);
            }
        });

        jLabel1.setText("Host:");

        ConnectButton.setText("Connect");
        ConnectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConnectButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("User:");

        jLabel3.setText("Pass:");

        Host.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                HostKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                HostKeyPressed(evt);
            }
        });

        User.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                UserKeyPressed(evt);
            }
        });

        Pass.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                PassFocusGained(evt);
            }
        });
        Pass.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                PassKeyPressed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Lucida Grande", 1, 17)); // NOI18N
        jLabel5.setText("Dicoogle GUI Connector");

        jLabel6.setIcon(new ImageIcon(getImage("icone_dicoogle_small.png")));

        jLabel7.setText("Version 0.5ALPHA");

        jLabel8.setIcon(new ImageIcon(getImage("ajax-loader.gif")));
        jLabel8.setText("Connecting...");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 255, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(33, 33, 33)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLabel4)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 218, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(layout.createSequentialGroup()
                                    .add(jLabel8)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 81, Short.MAX_VALUE)
                                    .add(ConnectButton))
                                .add(layout.createSequentialGroup()
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(jLabel2)
                                        .add(jLabel3)
                                        .add(jLabel1))
                                    .add(28, 28, 28)
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(Pass, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                                        .add(Host, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                                        .add(Port, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                                        .add(User, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)))))
                        .add(80, 80, 80))
                    .add(layout.createSequentialGroup()
                        .add(jLabel7)
                        .addContainerGap())))
            .add(layout.createSequentialGroup()
                .add(202, 202, 202)
                .add(jLabel5)
                .addContainerGap(222, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(jLabel5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel7)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 22, Short.MAX_VALUE)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(Host, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel1))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel4)
                            .add(Port, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(12, 12, 12)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel2)
                            .add(User, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel3)
                            .add(Pass, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(ConnectButton)
                            .add(jLabel8))
                        .add(37, 37, 37))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ConnectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConnectButtonActionPerformed
        if (Host.getText().length() == 0 || Port.getText().length() == 0
                || Pass.getPassword().length == 0 || User.getText().length() == 0)
        {
            JOptionPane.showMessageDialog(this, "You need to fill in all fields!",
                    "Error", JOptionPane.INFORMATION_MESSAGE);
            
        }
        else{
            jLabel8.setVisible(true);
            
            try{
                
                ConnectServer connect;
                try {
                    
                    connect = new ConnectServer(Host.getText(), Integer.valueOf(Port.getText()));
                    
                    String passwordHash;
                    if(isUsingDefaultPass){
                        passwordHash = ClientSettings.getInstance().getDefaultPassword();
                    }
                    else{
                        String passPlainText = new String(Pass.getPassword());
                        passwordHash = HashService.getSHA1Hash(passPlainText);
                    }
                    if (!connect.login(User.getText(), passwordHash)) {
                        jLabel8.setVisible(false);
                        JOptionPane.showMessageDialog(this, "The username or password is wrong!", "Wrong Username or Password", JOptionPane.ERROR_MESSAGE);
                    }
                    

                } catch (Exception ex) {
                   //LoggerFactory.getLogger(ConnectWindow.class).error(ex.getMessage(), ex);
                    JOptionPane.showMessageDialog(this, "Unable to connect to the GUI Server\n"+ex.getMessage(),
                    "Connection Error", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
                
            }
            catch(NumberFormatException ex){
                jLabel8.setVisible(false);

                JOptionPane.showMessageDialog(this, "Wrong port number!",
                    "Error", JOptionPane.ERROR_MESSAGE);
            }

        }
}//GEN-LAST:event_ConnectButtonActionPerformed

    private void HostKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_HostKeyTyped

    }//GEN-LAST:event_HostKeyTyped

    private void HostKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_HostKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            ConnectButton.doClick();
    }//GEN-LAST:event_HostKeyPressed

    private void PortKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_PortKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            ConnectButton.doClick();
    }//GEN-LAST:event_PortKeyPressed

    private void UserKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_UserKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            ConnectButton.doClick();
    }//GEN-LAST:event_UserKeyPressed

    private void PassKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_PassKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            ConnectButton.doClick();
    }//GEN-LAST:event_PassKeyPressed

    private void PassFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_PassFocusGained
        if(isUsingDefaultPass){
            Pass.setText("");
            isUsingDefaultPass = false;
        }
    }//GEN-LAST:event_PassFocusGained

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ConnectButton;
    private javax.swing.JTextField Host;
    private javax.swing.JPasswordField Pass;
    private javax.swing.JTextField Port;
    private javax.swing.JTextField User;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    // End of variables declaration//GEN-END:variables

}
